package servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import sessions.HelpManagerRemote;
import entities.HelpRequest;
import exceptions.FeedbackException;

/**
 * Servlet implementation class Feedback
 */
public class AddFeedback extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AddFeedback() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		int evaluation = Integer.parseInt(request.getParameter("evaluation"));
		String comment = request.getParameter("comment");
		int hrid = Integer.parseInt(request.getParameter("hrid"));
		try {
			Hashtable<String, String> env = new Hashtable<String, String>();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jnp.interfaces.NamingContextFactory");
			env.put(Context.PROVIDER_URL, "localhost:1099");
			InitialContext jndiContext = new InitialContext(env);
			Object ref = jndiContext.lookup("HelpManager/remote");
			HelpManagerRemote r = (HelpManagerRemote) ref;
			HelpRequest hr = r.fetch(hrid);
			try {
				r.addFeedback(evaluation, comment, hr);
				response.sendRedirect("./HelpReqs");
				return;
			} catch (FeedbackException e) {
				String error = "<font face='tahoma' size='2'>Feedback già presente.</font><br><font face='tahoma' size='2'><a href='./HelpReqs' style='color: blue; text-decoration: underline'>Torna all'elenco</a></font>";
				HttpSession session = request.getSession();
				session.setAttribute("error", error);
				response.sendRedirect("error.jsp");
				return;
			}
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}

}
